package com.apikey.auth.service.impl;

import com.apikey.auth.entity.ApiKey;
import com.apikey.auth.entity.History;
import com.apikey.auth.repository.ApiKeyRepository;
import com.apikey.auth.repository.HistoryRepository;
import com.apikey.auth.service.HistoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 历史记录服务实现类
 * 提供API Key历史记录的管理和查询功能的具体实现
 *
 * @author API Key Framework
 * @version 1.0
 */
@Service
public class HistoryServiceImpl implements HistoryService {

    @Autowired
    private ApiKeyRepository apiKeyRepository;

    @Autowired
    private HistoryRepository historyRepository;

    // 注意：这里不能直接注入ApiKeyService，会造成循环依赖
    // @Autowired
    // private ApiKeyService apiKeyService;

    /**
     * 记录API Key变更历史
     *
     * @param apiKey        API Key信息
     * @param operationType 操作类型
     * @param operatorId    操作者ID
     */
    @Override
    @Transactional
    public void recordHistory(ApiKey apiKey, String operationType, String operatorId) {
        recordChange(apiKey, operationType, operatorId, null);
    }

    /**
     * 记录API Key更新历史
     *
     * @param apiKey     API Key信息
     * @param operatorId 操作者ID
     */
    @Override
    @Transactional
    public void recordUpdate(ApiKey apiKey, String operatorId) {
        recordChange(apiKey, "UPDATE", operatorId, "API Key updated");
    }

    /**
     * 记录API Key变更历史（带变更原因）
     *
     * @param apiKey        API Key信息
     * @param operationType 操作类型
     * @param operatorId    操作者ID
     * @param changeReason  变更原因
     */
    @Override
    @Transactional
    public void recordChange(ApiKey apiKey, String operationType, String operatorId, String changeReason) {
        History history = new History(apiKey, operationType, operatorId);
        if (changeReason != null) {
            history.setChangeReason(changeReason);
        }

        try {
            historyRepository.save(history);
        } catch (Exception e) {
            // 记录历史失败不应该影响主业务流程
            // 可以记录日志或发送告警
            System.err.println("Failed to record history: " + e.getMessage());
        }
    }

    /**
     * 分页查询历史记录
     *
     * @param userId        用户ID
     * @param operatorId    操作者ID
     * @param operationType 操作类型
     * @param apiKeyValue   API Key值
     * @param startTime     开始时间
     * @param endTime       结束时间
     * @param pageable      分页参数
     * @return 分页结果
     */
    @Override
    public Page<ApiKey> findHistoryRecords(String userId, String operatorId, String operationType,
                                           String apiKeyValue, LocalDateTime startTime, LocalDateTime endTime,
                                           Pageable pageable) {

        Specification<ApiKey> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 只查询历史记录（已删除的记录）
            predicates.add(criteriaBuilder.equal(root.get("isDeleted"), true));

            if (userId != null && !userId.trim().isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("userId"), "%" + userId + "%"));
            }

            if (operatorId != null && !operatorId.trim().isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("operatorId"), "%" + operatorId + "%"));
            }

            if (operationType != null && !operationType.trim().isEmpty()) {
                predicates.add(criteriaBuilder.equal(root.get("operationType"), operationType));
            }

            if (apiKeyValue != null && !apiKeyValue.trim().isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("keyValue"), "%" + apiKeyValue + "%"));
            }

            if (startTime != null) {
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("updatedAt"), startTime));
            }

            if (endTime != null) {
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("updatedAt"), endTime));
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };

        return apiKeyRepository.findAll(spec, pageable);
    }

    /**
     * 根据ID查找历史记录
     *
     * @param id 历史记录ID
     * @return 历史记录
     */
    @Override
    public ApiKey findHistoryById(Long id) {
        // 这里应该返回历史记录对应的API Key信息
        return apiKeyRepository.findById(id).orElse(null);
    }

    /**
     * 比较两个历史记录的差异
     *
     * @param id1 第一个历史记录ID
     * @param id2 第二个历史记录ID
     * @return 差异信息
     */
    @Override
    public Map<String, Object> compareHistoryRecords(Long id1, Long id2) {
        ApiKey record1 = findHistoryById(id1);
        ApiKey record2 = findHistoryById(id2);

        if (record1 == null || record2 == null) {
            throw new IllegalArgumentException("历史记录不存在");
        }

        Map<String, Object> comparison = new HashMap<>();
        Map<String, Object> differences = new HashMap<>();

        // 比较各个字段
        compareField(differences, "名称", record1.getName(), record2.getName());
        compareField(differences, "权限", record1.getPermissions(), record2.getPermissions());
        compareField(differences, "状态", record1.getStatus(), record2.getStatus());
        compareField(differences, "每日限制", record1.getDailyLimit(), record2.getDailyLimit());
        compareField(differences, "每月限制", record1.getMonthlyLimit(), record2.getMonthlyLimit());
        compareField(differences, "过期时间", record1.getExpiresAt(), record2.getExpiresAt());
        compareField(differences, "描述", record1.getDescription(), record2.getDescription());

        comparison.put("record1", record1);
        comparison.put("record2", record2);
        comparison.put("differences", differences);
        comparison.put("hasDifferences", !differences.isEmpty());

        return comparison;
    }

    /**
     * 从历史记录恢复API Key
     *
     * @param historyId 历史记录ID
     * @return 恢复的API Key
     */
    @Override
    @Transactional
    public ApiKey restoreFromHistory(Long historyId) {
        ApiKey historyRecord = findHistoryById(historyId);
        if (historyRecord == null) {
            throw new IllegalArgumentException("历史记录不存在");
        }

        // 创建新的API Key实例
        ApiKey restoredApiKey = new ApiKey();
        BeanUtils.copyProperties(historyRecord, restoredApiKey);
        restoredApiKey.setId(null); // 清除ID，让数据库生成新的ID
        restoredApiKey.setIsDeleted(false);
        restoredApiKey.setCreatedAt(LocalDateTime.now());
        restoredApiKey.setUpdatedAt(LocalDateTime.now());

        try {
            ApiKey saved = apiKeyRepository.save(restoredApiKey);
            recordChange(saved, "RESTORE", "system", "从历史记录恢复");
            return saved;
        } catch (Exception e) {
            throw new RuntimeException("恢复API Key失败: " + e.getMessage());
        }
    }

    /**
     * 获取总历史记录数
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 总记录数
     */
    @Override
    public long getTotalHistoryCount(LocalDateTime startTime, LocalDateTime endTime) {
        Specification<ApiKey> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("isDeleted"), true));
            predicates.add(criteriaBuilder.between(root.get("updatedAt"), startTime, endTime));
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        return apiKeyRepository.count(spec);
    }

    /**
     * 获取指定操作类型的记录数
     *
     * @param operationType 操作类型
     * @param startTime     开始时间
     * @param endTime       结束时间
     * @return 记录数
     */
    @Override
    public long getOperationCount(String operationType, LocalDateTime startTime, LocalDateTime endTime) {
        Specification<ApiKey> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("isDeleted"), true));
            predicates.add(criteriaBuilder.equal(root.get("operationType"), operationType));
            predicates.add(criteriaBuilder.between(root.get("updatedAt"), startTime, endTime));
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };
        return apiKeyRepository.count(spec);
    }

    /**
     * 获取操作类型分布
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 操作类型分布
     */
    @Override
    public Map<String, Object> getOperationDistribution(LocalDateTime startTime, LocalDateTime endTime) {
        Map<String, Object> distribution = new HashMap<>();

        // 手动统计各操作类型
        List<String> labels = Arrays.asList("创建", "更新", "删除", "恢复");
        List<Long> data = Arrays.asList(
                getOperationCount("CREATE", startTime, endTime),
                getOperationCount("UPDATE", startTime, endTime),
                getOperationCount("DELETE", startTime, endTime),
                getOperationCount("RESTORE", startTime, endTime)
        );

        distribution.put("labels", labels);
        distribution.put("data", data);

        return distribution;
    }

    /**
     * 获取每日操作统计
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @return 每日操作统计
     */
    @Override
    public List<Map<String, Object>> getDailyOperationStats(LocalDateTime startTime, LocalDateTime endTime) {
        List<Map<String, Object>> dailyStats = new ArrayList<>();

        LocalDateTime current = startTime.toLocalDate().atStartOfDay();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        while (current.isBefore(endTime)) {
            LocalDateTime nextDay = current.plusDays(1);

            Map<String, Object> dayStats = new HashMap<>();
            dayStats.put("date", current.format(formatter));
            dayStats.put("create", getOperationCount("CREATE", current, nextDay));
            dayStats.put("update", getOperationCount("UPDATE", current, nextDay));
            dayStats.put("delete", getOperationCount("DELETE", current, nextDay));
            dayStats.put("total", getTotalHistoryCount(current, nextDay));

            dailyStats.add(dayStats);
            current = nextDay;
        }

        return dailyStats;
    }

    /**
     * 清理旧的历史记录
     *
     * @param days 保留天数
     * @return 删除的记录数
     */
    @Override
    @Transactional
    public int cleanupOldHistory(int days) {
        LocalDateTime cutoffTime = LocalDateTime.now().minusDays(days);
        return cleanupOldHistory(cutoffTime);
    }

    /**
     * 清理旧的历史记录
     *
     * @param beforeDate 删除此日期之前的记录
     * @return 删除的记录数
     */
    @Override
    @Transactional
    public int cleanupOldHistory(LocalDateTime beforeDate) {
        try {
            List<History> oldRecords = historyRepository.findOldDeletedRecords(beforeDate);
            if (!oldRecords.isEmpty()) {
                historyRepository.deleteAll(oldRecords);
                return oldRecords.size();
            }
            return 0;
        } catch (Exception e) {
            throw new RuntimeException("清理历史记录失败: " + e.getMessage());
        }
    }

    /**
     * 获取API Key的完整变更历史
     *
     * @param apiKeyValue API Key值
     * @return 变更历史列表
     */
    public List<ApiKey> getApiKeyTimeline(String apiKeyValue) {
        Specification<ApiKey> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("keyValue"), apiKeyValue));
            predicates.add(criteriaBuilder.equal(root.get("isDeleted"), true));
            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };

        return apiKeyRepository.findAll(spec, Sort.by(Sort.Direction.DESC, "updatedAt"));
    }

    /**
     * 比较字段差异
     *
     * @param differences 差异映射
     * @param fieldName   字段名称
     * @param value1      值1
     * @param value2      值2
     */
    private void compareField(Map<String, Object> differences, String fieldName, Object value1, Object value2) {
        if (!Objects.equals(value1, value2)) {
            Map<String, Object> fieldDiff = new HashMap<>();
            fieldDiff.put("old", value1);
            fieldDiff.put("new", value2);
            differences.put(fieldName, fieldDiff);
        }
    }

    /**
     * 多条件分页查询历史记录
     *
     * @param apiKeyId      API Key ID过滤
     * @param operatorId    操作者ID过滤
     * @param operationType 操作类型过滤
     * @param startTime     开始时间
     * @param endTime       结束时间
     * @param pageable      分页参数
     * @return 分页结果
     */
    @Override
    public Page<History> getHistory(Long apiKeyId, String operatorId, String operationType,
                                    LocalDateTime startTime, LocalDateTime endTime, Pageable pageable) {
        Specification<History> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("isDeleted"), false));

            if (apiKeyId != null) {
                predicates.add(criteriaBuilder.equal(root.get("keyValue"),
                        apiKeyRepository.findById(apiKeyId).map(ApiKey::getKeyValue).orElse("")));
            }
            if (operatorId != null && !operatorId.isEmpty()) {
                predicates.add(criteriaBuilder.equal(root.get("operatorId"), operatorId));
            }
            if (operationType != null && !operationType.isEmpty()) {
                predicates.add(criteriaBuilder.equal(root.get("operationType"), operationType));
            }
            if (startTime != null) {
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("updatedAt"), startTime));
            }
            if (endTime != null) {
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("updatedAt"), endTime));
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };

        return historyRepository.findAll(spec, pageable);
    }

    /**
     * 搜索历史记录
     *
     * @param keyword 关键词
     * @param page    页码
     * @param size    每页大小
     * @return 分页结果
     */
    @Override
    public Page<History> searchHistory(String keyword, int page, int size) {
        Specification<History> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("isDeleted"), false));

            if (keyword != null && !keyword.isEmpty()) {
                Predicate keywordPredicate = criteriaBuilder.or(
                        criteriaBuilder.like(root.get("name"), "%" + keyword + "%"),
                        criteriaBuilder.like(root.get("keyValue"), "%" + keyword + "%"),
                        criteriaBuilder.like(root.get("operatorId"), "%" + keyword + "%"),
                        criteriaBuilder.like(root.get("description"), "%" + keyword + "%")
                );
                predicates.add(keywordPredicate);
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };

        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "updatedAt"));
        return historyRepository.findAll(spec, pageable);
    }

    /**
     * 获取总操作数
     *
     * @return 总操作数
     */
    @Override
    public long getTotalOperationCount() {
        return apiKeyRepository.countByIsDeleted(true);
    }

    /**
     * 获取今日操作数
     *
     * @return 今日操作数
     */
    @Override
    public long getTodayOperationCount() {
        LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
        LocalDateTime endOfDay = startOfDay.plusDays(1);
        return getTotalHistoryCount(startOfDay, endOfDay);
    }

    /**
     * 获取顶级操作者
     *
     * @param limit 限制数量
     * @return 顶级操作者列表
     */
    @Override
    public List<Map<String, Object>> getTopOperators(int limit) {
        List<Map<String, Object>> topOperators = new ArrayList<>();

        // 简单实现，实际项目中可能需要更复杂的查询
        List<String> operators = Arrays.asList("admin", "user1", "user2", "system");

        for (String operator : operators) {
            if (topOperators.size() >= limit) break;

            long count = apiKeyRepository.countByOperatorIdAndIsDeleted(operator, true);
            if (count > 0) {
                Map<String, Object> operatorData = new HashMap<>();
                operatorData.put("operator", operator);
                operatorData.put("count", count);
                topOperators.add(operatorData);
            }
        }

        return topOperators;
    }

    /**
     * 获取变更趋势
     *
     * @param days 天数
     * @return 变更趋势数据
     */
    @Override
    public List<Map<String, Object>> getChangeTrend(int days) {
        List<Map<String, Object>> trend = new ArrayList<>();
        LocalDateTime endTime = LocalDateTime.now();
        LocalDateTime startTime = endTime.minusDays(days);

        return getDailyOperationStats(startTime, endTime);
    }

    /**
     * 导出历史记录
     *
     * @param format        导出格式
     * @param apiKeyId      API Key ID
     * @param operatorId    操作者ID
     * @param operationType 操作类型
     * @param startTime     开始时间
     * @param endTime       结束时间
     * @return 导出数据
     */
    @Override
    public String exportHistory(String format, Long apiKeyId, String operatorId,
                                String operationType, LocalDateTime startTime, LocalDateTime endTime) {
        Specification<ApiKey> spec = (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();
            predicates.add(criteriaBuilder.equal(root.get("isDeleted"), true));

            if (apiKeyId != null) {
                predicates.add(criteriaBuilder.equal(root.get("id"), apiKeyId));
            }
            if (operatorId != null && !operatorId.isEmpty()) {
                predicates.add(criteriaBuilder.equal(root.get("operatorId"), operatorId));
            }
            if (operationType != null && !operationType.isEmpty()) {
                predicates.add(criteriaBuilder.equal(root.get("operationType"), operationType));
            }
            if (startTime != null) {
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("updatedAt"), startTime));
            }
            if (endTime != null) {
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("updatedAt"), endTime));
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        };

        List<ApiKey> historyRecords = apiKeyRepository.findAll(spec, Sort.by(Sort.Direction.DESC, "updatedAt"));

        if ("csv".equalsIgnoreCase(format)) {
            return exportHistoryToCsv(historyRecords);
        }

        throw new IllegalArgumentException("不支持的导出格式: " + format);
    }

    /**
     * 根据ID查找历史记录
     *
     * @param id 记录ID
     * @return 历史记录
     */
    @Override
    public History findById(Long id) {
        return historyRepository.findById(id).orElse(null);
    }

    /**
     * 比较两个历史记录
     *
     * @param id1 历史记录ID1
     * @param id2 历史记录ID2
     * @return 比较结果
     */
    @Override
    public Map<String, Object> compareHistory(Long id1, Long id2) {
        History history1 = historyRepository.findById(id1).orElse(null);
        History history2 = historyRepository.findById(id2).orElse(null);

        Map<String, Object> result = new HashMap<>();

        if (history1 == null || history2 == null) {
            result.put("success", false);
            result.put("message", "历史记录不存在");
            return result;
        }

        Map<String, Object> differences = new HashMap<>();

        // 比较各个字段
        compareField(differences, "操作类型", history1.getOperationType(), history2.getOperationType());
        compareField(differences, "操作者", history1.getOperatorId(), history2.getOperatorId());
        compareField(differences, "操作时间", history1.getUpdatedAt(), history2.getUpdatedAt());
        compareField(differences, "变更原因", history1.getChangeReason(), history2.getChangeReason());

        result.put("success", true);
        result.put("history1", history1);
        result.put("history2", history2);
        result.put("differences", differences);

        return result;
    }

    /**
     * 查询历史记录（支持多条件过滤）
     *
     * @param apiKeyId   API Key ID过滤
     * @param operatorId 操作者ID过滤
     * @param operation  操作类型过滤
     * @param startTime  开始时间
     * @param endTime    结束时间
     * @param pageable   分页参数
     * @return 分页结果
     */
    @Override
    public Page<History> findHistory(Long apiKeyId, String operatorId, String operation,
                                     LocalDateTime startTime, LocalDateTime endTime, Pageable pageable) {
        return historyRepository.findAll((Specification<History>) (root, query, criteriaBuilder) -> {
            List<Predicate> predicates = new ArrayList<>();

            // 添加 isDeleted = false 条件
            predicates.add(criteriaBuilder.equal(root.get("isDeleted"), false));

            if (operatorId != null && !operatorId.trim().isEmpty()) {
                predicates.add(criteriaBuilder.like(root.get("operatorId"), "%" + operatorId + "%"));
            }

            if (operation != null && !operation.trim().isEmpty()) {
                predicates.add(criteriaBuilder.equal(root.get("operationType"), operation));
            }

            if (startTime != null) {
                predicates.add(criteriaBuilder.greaterThanOrEqualTo(root.get("updatedAt"), startTime));
            }

            if (endTime != null) {
                predicates.add(criteriaBuilder.lessThanOrEqualTo(root.get("updatedAt"), endTime));
            }

            return criteriaBuilder.and(predicates.toArray(new Predicate[0]));
        }, pageable);
    }

    /**
     * 获取操作类型统计信息
     *
     * @return 操作类型统计列表
     */
    @Override
    public List<Map<String, Object>> getOperationTypeStats() {
        try {
            List<Object[]> results = historyRepository.getOperationTypeDistribution();
            List<Map<String, Object>> stats = new ArrayList<>();

            for (Object[] result : results) {
                Map<String, Object> stat = new HashMap<>();
                stat.put("operationType", result[0]);
                stat.put("count", result[1]);
                stat.put("label", getOperationTypeLabel((String) result[0]));
                stats.add(stat);
            }

            return stats;
        } catch (Exception e) {
            // 如果数据库查询失败，返回默认数据
            List<Map<String, Object>> defaultStats = new ArrayList<>();

            Map<String, Object> createStat = new HashMap<>();
            createStat.put("operationType", "CREATE");
            createStat.put("count", 0L);
            createStat.put("label", "创建操作");
            defaultStats.add(createStat);

            Map<String, Object> updateStat = new HashMap<>();
            updateStat.put("operationType", "UPDATE");
            updateStat.put("count", 0L);
            updateStat.put("label", "更新操作");
            defaultStats.add(updateStat);

            Map<String, Object> deleteStat = new HashMap<>();
            deleteStat.put("operationType", "DELETE");
            deleteStat.put("count", 0L);
            deleteStat.put("label", "删除操作");
            defaultStats.add(deleteStat);

            return defaultStats;
        }
    }

    /**
     * 导出历史记录为CSV格式
     *
     * @param historyRecords 历史记录列表
     * @return CSV字符串
     */
    private String exportHistoryToCsv(List<ApiKey> historyRecords) {
        StringBuilder csv = new StringBuilder();

        // CSV头部
        csv.append("ID,名称,API Key,权限,状态,操作类型,操作者,操作时间,描述\n");

        // 数据行
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        for (ApiKey record : historyRecords) {
            csv.append(record.getId()).append(",")
                    .append(escapeCSV(record.getName())).append(",")
                    .append(escapeCSV(record.getKeyValue())).append(",")
                    .append(escapeCSV(record.getPermissions())).append(",")
                    .append(escapeCSV(record.getStatus())).append(",")
                    .append(escapeCSV(getOperationTypeLabel(record.getOperationType()))).append(",")
                    .append(escapeCSV(record.getOperatorId())).append(",")
                    .append(record.getUpdatedAt().format(formatter)).append(",")
                    .append(escapeCSV(record.getDescription())).append("\n");
        }

        return csv.toString();
    }

    /**
     * 转义CSV字段
     *
     * @param value 字段值
     * @return 转义后的值
     */
    private String escapeCSV(String value) {
        if (value == null) {
            return "";
        }
        if (value.contains(",") || value.contains("\"") || value.contains("\n")) {
            return "\"" + value.replace("\"", "\"\"") + "\"";
        }
        return value;
    }

    /**
     * 获取操作类型标签
     *
     * @param operationType 操作类型
     * @return 操作类型标签
     */
    private String getOperationTypeLabel(String operationType) {
        switch (operationType) {
            case "CREATE":
                return "创建";
            case "UPDATE":
                return "更新";
            case "DELETE":
                return "删除";
            case "RESTORE":
                return "恢复";
            default:
                return operationType;
        }
    }
}